package com.yupi.yupicturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.yupicturebackend.common.DeleteRequest;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import com.yupi.yupicturebackend.manager.CosManager;
import com.yupi.yupicturebackend.manager.FileManager;
import com.yupi.yupicturebackend.manager.upload.FilePictureUpload;
import com.yupi.yupicturebackend.manager.upload.PictureUploadTemplate;
import com.yupi.yupicturebackend.manager.upload.UrlPictureUpload;
import com.yupi.yupicturebackend.model.dto.file.UploadPictureResult;
import com.yupi.yupicturebackend.model.dto.picture.*;
import com.yupi.yupicturebackend.model.entity.Picture;
import com.yupi.yupicturebackend.model.entity.Space;
import com.yupi.yupicturebackend.model.entity.User;
import com.yupi.yupicturebackend.model.enums.PictureReviewStatusEnums;
import com.yupi.yupicturebackend.model.enums.UserRoleEnums;
import com.yupi.yupicturebackend.model.vo.PictureVo;
import com.yupi.yupicturebackend.service.PictureService;
import com.yupi.yupicturebackend.mapper.PictureMapper;
import com.yupi.yupicturebackend.service.SpaceService;
import com.yupi.yupicturebackend.service.UserService;
import com.yupi.yupicturebackend.util.ColorSimilarUtils;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author MK
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2024-12-15 18:22:15
 */
@Service
@Slf4j
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
        implements PictureService {
    @Resource
    private FileManager fileManager;
    @Resource
    private UserService userService;
    @Resource
    private FilePictureUpload filePictureUpload;
    @Resource
    private UrlPictureUpload urlPictureUpload;
    @Resource
    private CosManager cosManager;
    @Resource
    private SpaceService spaceService;
    @Resource
    private TransactionTemplate transactionTemplate;

    /**
     * 用户上传
     *
     * @param inputSource
     * @param pictureUploudRequest
     * @param loginUser
     * @return
     */
    @Override
    public PictureVo uploadPicture(Object inputSource, PictureUploudRequest pictureUploudRequest, User loginUser) {
        //1.校验文件
        ThrowUtils.throwIf(inputSource == null, ErrorCode.PARAMS_ERROR, "上传文件为空");
        //2，校验是否上传了文件id
        Picture pictureResult = new Picture();
        long pictureId = pictureUploudRequest.getId();
        if (pictureId != 0) {
            Picture oldPicture = this.getById(pictureId);
            if (oldPicture != null) {
                this.checkPictureAuth(oldPicture, loginUser);
                this.ClearPictureFile(oldPicture);
                this.baseMapper.deleteById(pictureId);
            }
        }
        //3.判断上传前空间额度是否超额
        Long spaceId = pictureUploudRequest.getSpaceId();
        if (spaceId != null) {
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space.getTotalCount() >= space.getMaxCount(), ErrorCode.PARAMS_ERROR, "空间图片数已满");
            ThrowUtils.throwIf(space.getTotalSize() >= space.getMaxSize(), ErrorCode.PARAMS_ERROR, "空间容量已满");
        }
        //图片审核策略
        this.PictureReviewParams(pictureResult, loginUser);
        //3.上传图片并得到上传结果的参数
        //3.1将用户id作为路径前缀

        String prefix = String.format("public/%s", loginUser.getId());
        if (pictureUploudRequest.getSpaceId() != null) {
            prefix = String.format("space/%s", loginUser.getId());
        }

        PictureUploadTemplate pictureUploadTemplate = null;
        if (inputSource instanceof MultipartFile) {
            pictureUploadTemplate = filePictureUpload;
        }
        if (inputSource instanceof String) {
            pictureUploadTemplate = urlPictureUpload;
        }
        //
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSource, prefix);
        pictureResult.setUrl(uploadPictureResult.getUrl());
        pictureResult.setThumbnailUrl(uploadPictureResult.getThumbnailUrl());
        if (pictureUploudRequest.getName() != null) {
            pictureResult.setName(pictureUploudRequest.getName());
        } else {
            pictureResult.setName(uploadPictureResult.getPicName());
        }
        pictureResult.setSpaceId(pictureUploudRequest.getSpaceId());
        pictureResult.setPicSize(uploadPictureResult.getPicSize());
        pictureResult.setPicWidth(uploadPictureResult.getPicWidth());
        pictureResult.setPicHeight(uploadPictureResult.getPicHeight());
        pictureResult.setPicScale(uploadPictureResult.getPicScale());
        pictureResult.setPicFormat(uploadPictureResult.getPicFormat());
        pictureResult.setUserId(loginUser.getId());
        pictureResult.setPicColor(uploadPictureResult.getPicColor());
        if (pictureId != 0) {
            pictureResult.setId(pictureId);
            pictureResult.setEditTime(DateUtil.date(new Date()));
        }
        //开启事务
        Boolean execute = transactionTemplate.execute(status -> {
            boolean result = this.saveOrUpdate(pictureResult);
            spaceService.lambdaUpdate().eq(Space::getId, spaceId)
                    .setSql("totalCount=totalCount+1")
                    .setSql("totalSize=totalSize+{picSize}", pictureResult.getPicSize())
                    .update();
            return result;
        });
        if (!execute) {
            ThrowUtils.throwIf(false, ErrorCode.PARAMS_ERROR, "上传文件失败");
        }

        return PictureVo.objToVo(pictureResult);
    }

    /**
     * 更新图片信息（仅管理员可用）
     */
    @Override
    public boolean updatePicture(PictureUpdateRequest pictureUpdateRequest, HttpServletRequest httpServletRequest) {
        User loginUser = userService.getLoginUser(httpServletRequest);
        ThrowUtils.throwIf(pictureUpdateRequest == null, ErrorCode.PARAMS_ERROR, "更新图片信息参数为空");
        Long id = pictureUpdateRequest.getId();
        ThrowUtils.throwIf(id == null, ErrorCode.PARAMS_ERROR, "更新图片Id不能为空");
        boolean exists = this.lambdaQuery().eq(Picture::getId, id).exists();
        if (!exists) {
            ThrowUtils.throwIf(false, ErrorCode.PARAMS_ERROR, "需要更新图片信息不存在");
        }
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureUpdateRequest, picture);
        picture.setTags(JSONUtil.toJsonStr(pictureUpdateRequest.getTags()));
        validPicture(picture);
        //管理员添加的图片可以跳过审核
        this.PictureReviewParams(picture, userService.getLoginUser(httpServletRequest));
        UpdateWrapper<Picture> PictureUpdateWrapper = new UpdateWrapper<>();
        PictureUpdateWrapper.eq("id", id);
        int update = this.baseMapper.update(picture, PictureUpdateWrapper);
        if (update == 0) {
            ThrowUtils.throwIf(false, ErrorCode.PARAMS_ERROR, "更新图片信息失败");
        }
        return true;
    }

    /**
     * 更新图片信息（用户可用）
     */
    @Override
    public boolean updatePictureVo(PictureEditRequest pictureEditRequest, HttpServletRequest httpServletRequest) {
        User loginUser = userService.getLoginUser(httpServletRequest);
        ThrowUtils.throwIf(pictureEditRequest == null, ErrorCode.PARAMS_ERROR, "更新图片信息参数为空");
        Long id = pictureEditRequest.getId();
        ThrowUtils.throwIf(id == null, ErrorCode.PARAMS_ERROR, "更新图片Id不能为空");
        Picture oldPicture = this.lambdaQuery().eq(Picture::getId, id).getEntity();
        if (oldPicture == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "需要更新图片信息不存在");
        }
        this.checkPictureAuth(oldPicture, loginUser);
        Picture picture = new Picture();
        picture.setName(pictureEditRequest.getName());
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        picture.setIntroduction(pictureEditRequest.getIntroduction());
        picture.setCategory(pictureEditRequest.getCategory());
        picture.setEditTime(DateUtil.date(new Date()));
        picture.setUserId(loginUser.getId());
        validPicture(picture);
        this.PictureReviewParams(picture, userService.getLoginUser(httpServletRequest));
        UpdateWrapper<Picture> PictureUpdateWrapper = new UpdateWrapper<>();
        PictureUpdateWrapper.eq("id", id);
        int update = this.baseMapper.update(picture, PictureUpdateWrapper);
        if (update == 0) {
            ThrowUtils.throwIf(false, ErrorCode.PARAMS_ERROR, "更新图片信息失败");
        }
        return true;
    }

    /**
     * 根据id删除图片
     */
    @Override
    @Synchronized
    public boolean deletePicture(DeleteRequest deleteRequest, HttpServletRequest request) {
        Long id = deleteRequest.getId();
        ThrowUtils.throwIf(id == null, ErrorCode.PARAMS_ERROR, "删除图片Id不能为空");
        Picture pictureById = this.getPictureById(id);
        if (pictureById == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图片不存在");
        }
        //校验权限
        User user = userService.getLoginUser(request);
        Picture oldPicture = this.getById(id);
        this.checkPictureAuth(oldPicture, user);
        Long spaceId = oldPicture.getSpaceId();
        this.ClearPictureFile(pictureById);
        this.removeById(id);
        if (spaceId != null) {
            //开启事务
            Boolean execute = transactionTemplate.execute(status -> {
                this.ClearPictureFile(pictureById);
                this.removeById(id);
                spaceService.lambdaUpdate().eq(Space::getId, spaceId)
                        .setSql("totalCount=totalCount-1")
                        .setSql("totalSize=totalSize-{picSize}", oldPicture.getPicSize())
                        .update();
                return true;
            });
            return execute;
        }
        return true;
    }

    /**
     * 根据id查询图片信息(未脱敏)
     */
    @Override
    public Picture getPictureById(Long id) {
        ThrowUtils.throwIf(id == null, ErrorCode.PARAMS_ERROR, "查询图片Id不能为空");
        boolean exists = this.lambdaQuery().eq(Picture::getId, id).exists();
        if (!exists) {
            ThrowUtils.throwIf(false, ErrorCode.PARAMS_ERROR, "需要查询图片不存在");
        }
        Picture picture = this.getById(id);
        return picture;
    }

    /**
     * 根据id查询图片信息(脱敏)
     */
    @Override
    public PictureVo getPictureVoById(Long id) {
        ThrowUtils.throwIf(id == null, ErrorCode.PARAMS_ERROR, "查询图片Id不能为空");
        boolean exists = this.lambdaQuery().eq(Picture::getId, id).exists();
        if (!exists) {
            ThrowUtils.throwIf(false, ErrorCode.PARAMS_ERROR, "需要查询图片不存在");
        }
        Picture picture = this.getById(id);
        PictureVo pictureVo = new PictureVo();
        BeanUtils.copyProperties(picture, pictureVo);
        pictureVo.setTags(JSONUtil.toList(picture.getTags(), String.class));
        return pictureVo;
    }

    /**
     * 分页获取图片的封装
     *
     * @param picturePage
     * @param request
     * @return
     */
    @Override
    public Page<PictureVo> getPictureVoPage(Page<Picture> picturePage, HttpServletRequest request) {
        //1.校验参数
        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVo> pictureVoPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollectionUtils.isEmpty(pictureList)) {
            return pictureVoPage;
        }
        //2.封装数据
        List<PictureVo> pictureVoList = pictureList.stream().map(picture -> PictureVo.objToVo(picture)).collect(Collectors.toList());
        //3.获取用户id列表
        Set<Long> idSet = pictureVoList.stream().map(PictureVo::getUserId).collect(Collectors.toSet());
        //4.通过用户id列表查询用户信息，并转为map形式key为userId，Value为List<User>
        List<User> users = userService.listByIds(idSet);
        Map<Long, List<User>> userIdUserMap = users.stream().collect(Collectors.groupingBy(User::getId));
        //5，将获取的值放入Vo中，并返回
        pictureVoList.forEach(pictureVo -> {
            Long id = pictureVo.getUserId();
            User user = null;
            if (userIdUserMap.containsKey(id)) {
                user = userIdUserMap.get(id).get(0);
            }
            pictureVo.setUserVo(userService.getUserVO(user));
        });
        pictureVoPage.setRecords(pictureVoList);
        return pictureVoPage;
    }

    /**
     * 上传图片（批量）
     */
    @Override
    public List<PictureVo> uploadPictureByBatch(PictureUploudByBatchRequest pictureUploudByBatchRequest, User loginUser) {
        //校验参数
        Long count = pictureUploudByBatchRequest.getCount();
        String searchText = pictureUploudByBatchRequest.getSearchText();
        String name = pictureUploudByBatchRequest.getName();
        ThrowUtils.throwIf(count > 30, ErrorCode.PARAMS_ERROR, "一次抓取数量最大为30");
        //获取内容
        String url = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
        Document document;
        try {
            //通过Jsoup获取页面连接的得到页面内容
            document = Jsoup.connect(url).get();
        } catch (IOException e) {
            log.error("页面获取失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "页面获取失败");
        }
        //解析内容，得到想要的部分
        document.getElementsByClass("dgControl").first();
        if (ObjUtil.isEmpty(document)) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "获取元素失败");
        }
        //获取图片信息
        Elements select = document.select("img.mimg");
        int upload = 0;
        List<PictureVo> pictureVoList = new ArrayList<>();
        //循环遍历图片信息
        for (Element element : select) {
            String fileUrl = element.attr("src");
            if (StrUtil.isBlank(fileUrl)) {
                log.info("id为{}的图片未查询到", fileUrl);
                upload++;
                continue;
            }
            //防止转义字符与对象存储冲突问题
            int i = fileUrl.indexOf("?");
            if (i > -1) {
                fileUrl = fileUrl.substring(0, i);
            }
            //上传图片
            try {
                PictureUploudRequest pictureUploudRequest = new PictureUploudRequest();
                pictureUploudRequest.setUrl(fileUrl);
                pictureUploudRequest.setName(name);
                PictureVo pictureVo = this.uploadPicture(fileUrl, pictureUploudRequest, loginUser);
                pictureVoList.add(pictureVo);
                upload++;
                log.info("图片上传成功{}", pictureVo.getId());
            } catch (Exception e) {
                log.error("图片上传失败", e);
            }
            if (upload >= count) {
                break;
            }
        }
        return pictureVoList;
    }

    /**
     * 删除图片文件
     *
     * @param oldPicture
     */
    @Override
    public void ClearPictureFile(Picture oldPicture) {
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.SYSTEM_ERROR, "删除条件错误");
        String url = oldPicture.getUrl();
        Long count = this.lambdaQuery().eq(Picture::getUrl, url).count();
        //如果图片被多条记录使用不删除（本项目不涉及多条记录仅练习）
        if (count == 1) {
            log.info("删除的图片url{}", url);
            cosManager.deleteObject(url);
        }
        String thumbnailUrl = oldPicture.getThumbnailUrl();
        log.info("删除的图片thumbnailUrl{}", thumbnailUrl);
        cosManager.deleteObject(thumbnailUrl);
    }

    /**
     * 校验参数
     *
     * @param picture
     */
    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        //id
        Long id = picture.getId();
        if (ObjUtil.isEmpty(id)) {
            ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR, "id不能为空");
        }
        //url
        if (StrUtil.isNotBlank(picture.getUrl())) {
            ThrowUtils.throwIf(picture.getUrl().length() > 1024, ErrorCode.PARAMS_ERROR, "url长度不能超过1024");
        }
        //introduction
        if (StrUtil.isNotBlank(picture.getIntroduction())) {
            ThrowUtils.throwIf(picture.getIntroduction().length() > 800, ErrorCode.PARAMS_ERROR, "介绍长度不能超过800");
        }
    }

    /**
     * 获取查询条件
     *
     * @param pictureQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        Long spaceId = pictureQueryRequest.getSpaceId();
        boolean needSpaceId = pictureQueryRequest.isNeedSpaceId();
        Date endTime = pictureQueryRequest.getEndTime();
        Date startTime = pictureQueryRequest.getStartTime();
        // 从多字段中搜索
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件
            // and (name like "%xxx%" or introduction like "%xxx%")
            queryWrapper.and(
                    qw -> qw.like("name", searchText)
                            .or()
                            .like("introduction", searchText)
            );
        }
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        queryWrapper.isNull(needSpaceId, "SpaceId");
//        >=
        queryWrapper.ge(ObjUtil.isNotEmpty(startTime), "editTime", startTime);
//        <
        queryWrapper.lt(ObjUtil.isNotEmpty(endTime), "editTime", endTime);
        // JSON 数组查询
        if (CollUtil.isNotEmpty(tags)) {
            /* and (tag like "%\"Java\"%" and like "%\"Python\"%") */
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * 图片审核
     *
     * @param pictureReviewRequest
     * @return boolean
     */

    @Override
    public void PictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
        //1.校验参数
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR);
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        PictureReviewStatusEnums enumByValue = PictureReviewStatusEnums.getEnumByValue(reviewStatus);
        if (enumByValue == null || reviewStatus == null || PictureReviewStatusEnums.REVIEW.equals(enumByValue)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //2.判断图片是否存在
        Long id = pictureReviewRequest.getId();
        Picture oldPicture = this.getById(id);
        if (oldPicture == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "图片不存在");
        }
        //3.判断图片是否已经审核
        if (oldPicture.getReviewStatus() != null && !PictureReviewStatusEnums.REVIEW.equals(enumByValue)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "图片已经审核过了");
        }
        //4.更新图片审核状态
        Picture picture = new Picture();
        BeanUtil.copyProperties(oldPicture, picture);
        picture.setReviewStatus(reviewStatus);
        picture.setReviewMessage(pictureReviewRequest.getReviewMessage());
        picture.setReviewTime(new Date());
        this.updateById(picture);
    }

    /**
     * 填充审核参数
     *
     * @param loginUser
     */
    @Override
    public void PictureReviewParams(Picture picture, User loginUser) {
        String userRole = loginUser.getUserRole();
        if (userRole.equals(UserRoleEnums.ADMIN.getValue())) {
            picture.setReviewStatus(PictureReviewStatusEnums.PASS.getValue());
            picture.setReviewerId(loginUser.getId());
            picture.setReviewMessage("管理员自动过审");
        } else {
            picture.setReviewStatus(PictureReviewStatusEnums.REVIEW.getValue());
        }
        picture.setReviewTime(new Date());
    }

    /**
     * 校验用户权限
     *
     * @param
     * @return
     */
    @Override
    public void checkPictureAuth(Picture picture, User loginUser) {
        Long spaceId = picture.getSpaceId();
        Long id = loginUser.getId();
        //如果是公共空间，仅本人和管理员可以操作//如果是私有空间仅本人可以操作
        if (spaceId == null) {
            if (!userService.isAdmin(id) && !id.equals(picture.getUserId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限操作");
            }
        } else {
            if (!id.equals(picture.getUserId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限操作");
            }
        }
    }

    @Override
    public List<PictureVo> searchPictureByColor(Long spaceId, String picColor, User loginUser) {
        // 1. 校验参数
        ThrowUtils.throwIf(spaceId == null || StrUtil.isBlank(picColor), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 2. 校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!loginUser.getId().equals(space.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
        }
        // 3. 查询该空间下所有图片（必须有主色调）
        List<Picture> pictureList = this.lambdaQuery()
                .eq(Picture::getSpaceId, spaceId)
                .isNotNull(Picture::getPicColor)
                .list();
        // 如果没有图片，直接返回空列表
        if (CollUtil.isEmpty(pictureList)) {
            return Collections.emptyList();
        }
        // 将目标颜色转为 Color 对象
        Color targetColor = Color.decode(picColor);
        // 4. 计算相似度并排序
        List<Picture> sortedPictures = pictureList.stream()
                .sorted(Comparator.comparingDouble(picture -> {
                    // 提取图片主色调
                    String hexColor = picture.getPicColor();
                    // 没有主色调的图片放到最后
                    if (StrUtil.isBlank(hexColor)) {
                        return Double.MAX_VALUE;
                    }
                    Color pictureColor = Color.decode(hexColor);
                    // 越大越相似
                    return -ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
                }))
                // 取前 12 个
                .limit(12)
                .collect(Collectors.toList());

        // 转换为 PictureVO
        return sortedPictures.stream()
                .map(PictureVo::objToVo)
                .collect(Collectors.toList());
    }

    /**
     * 分批编辑图片信息（标签和类型）
     */
    @Override
    public boolean PictureEditByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
        //1.1校验参数信息
        ThrowUtils.throwIf(pictureEditByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        List<String> tags = pictureEditByBatchRequest.getTags();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        String category = pictureEditByBatchRequest.getCategory();
        // 批量重命名
        String nameRule = pictureEditByBatchRequest.getNameRule();
        ThrowUtils.throwIf(CollUtil.isEmpty(pictureIdList), ErrorCode.PARAMS_ERROR, "图片id列表不能为空");
        ThrowUtils.throwIf(ObjUtil.isEmpty(loginUser), ErrorCode.FORBIDDEN_ERROR, "用户未登录");
        //1.2校验用户权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!loginUser.getId().equals(space.getUserId())){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
        }
        //1.3校验图片是否存在
        List<Picture> pictureList = this.lambdaQuery()
                .select(Picture::getId, Picture::getSpaceId)
                .eq(Picture::getSpaceId, spaceId)
                .in(Picture::getId, pictureIdList)
                .list();
        fillPictureWithNameRule(pictureList, nameRule);
        ThrowUtils.throwIf(CollUtil.isEmpty(pictureList), ErrorCode.NOT_FOUND_ERROR, "图片不存在");
        //2.2遍历图片信息并修改
        pictureList.forEach(picture -> {
            if (CollUtil.isNotEmpty(tags)){
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
            if (StrUtil.isNotBlank(category)) {
                picture.setCategory(category);
            }
        });
        //3.1上传修改结果到数据库
        boolean updateBatchById = this.updateBatchById(pictureList);
        return updateBatchById;
    }
    /**
     * nameRule 格式：图片{序号}
     *
     * @param pictureList
     * @param nameRule
     */
    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        if (CollUtil.isEmpty(pictureList) || StrUtil.isBlank(nameRule)) {
            return;
        }
        long count = 1;
        try {
            for (Picture picture : pictureList) {
                String pictureName = nameRule.replaceAll("\\{序号}", String.valueOf(count++));
                picture.setName(pictureName);
            }
        } catch (Exception e) {
            log.error("名称解析错误", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "名称解析错误");
        }
    }

}




